package controllers

import com.jfinal.core.ActionKey
import com.jfinal.core.Controller
import base.Message
import base.State
import utils.ResUtils

//@Before(UserTokenCheckValidator::class)
class ResController: Controller(){
    companion object{
        val TAG = ResController::class.simpleName!!
        const val FILE_NAME = "file_name"
        const val FILE = "file"
        const val FILE_MD5 = "file_md5"
    }

    fun avatar(){
        val name = get(0)
        val path = "pictures/avatars/$name"
        renderFile(path)
    }

    fun goods(){
        val name = get(0)
        val path = "pictures/goods/$name"
        renderFile(path)
    }

    @ActionKey("/res/upload/avatar")
    fun uploadAvatar(){
        val upFile = getFile(FILE)
        val fileMD5 = get(FILE_MD5)
        val path = ResUtils.saveAvatar(upFile, fileMD5)
        if (!path.isNullOrEmpty()){
            val message = Message(State.STATE_SUCCESS, data = path)
            renderJson(message)
        } else {
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_RES_UPLOAD_FAIL))
            renderJson(message)
        }
    }

    @ActionKey("/res/upload/goods")
    fun uploadGoodsPic(){
        val upFile = getFile(FILE)
        val fileMD5 = get(FILE_MD5)
        val path = ResUtils.saveGoodsPic(upFile, fileMD5)
        if (!path.isNullOrEmpty()){
            val message = Message(State.STATE_SUCCESS, data = path)
            renderJson(message)
        } else {
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_RES_UPLOAD_FAIL))
            renderJson(message)
        }
    }


}